<template>
	<div class="pound-container">

		<div class="pound-bottom">

			<el-card>
				<template #header>
					<div class="card-header" style="font-size: 24px;font-weight: 550;">
						<span>地磅历史数据</span>
					</div>
				</template>

				<el-form :inline="true" :model="formInline" class="demo-form-inline">
					<el-form-item label="过磅时间">
						<el-date-picker v-model="formInline.weighingDate" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
							type="date" placeholder="请选择过磅时间" style="width: 120px" />
					</el-form-item>
					<el-form-item label="车牌号">
						<el-input v-model="formInline.autoLicense" placeholder="请输入车牌号" clearable
							style="width: 120px" />
					</el-form-item>
					<el-form-item label="货物名称">
						<el-input v-model="formInline.cargoName" placeholder="请输入货物名称" clearable style="width: 120px" />
					</el-form-item>

					<!-- 新增：发货单位（下拉选择，复用现有caiOptions厂家列表） -->
					<el-form-item label="发货单位">
						<el-select v-model="formInline.shippingCompanyId" placeholder="请选择发货单位" style="width: 140px"
							clearable>
							<el-option v-for="item in caiOptions" :key="item.id" :label="item.companyName"
								:value="item.id" />
						</el-select>
					</el-form-item>

					<!-- 新增：收货单位（下拉选择，复用现有xiaoOptions厂家列表） -->
					<el-form-item label="收货单位">
						<el-select v-model="formInline.receivingCompanyId" placeholder="请选择收货单位" style="width: 140px"
							clearable>
							<el-option v-for="item in xiaoOptions" :key="item.id" :label="item.companyName"
								:value="item.id" />
						</el-select>
					</el-form-item>
					<el-form-item label="过磅状态">


						<el-select v-model="formInline.weightStatus" placeholder="请选择过磅状态" style="width: 140px"
							clearable>
							<el-option v-for="item in options" :key="item.value" :label="item.label"
								:value="item.value" />
						</el-select>
					</el-form-item>

					<el-form-item>
						<el-button type="primary" @click="onSubmit">查 询</el-button>
						<el-button type="default" @click="handleReset" style="margin-left: 8px;">重 置</el-button>
					</el-form-item>
				</el-form>



				<el-table :data="tableData" border style="width: 100%">
					<el-table-column prop="time" label="时间" width="140">
						<template #default="{row}">

							<span>{{ row.updateTime ||'-'}}</span>
						</template>
					</el-table-column>
					<el-table-column prop="autoLicense" label="车牌号" width="120">
						<template #default="{row}">
							<el-input v-if="row.isEditing" v-model="row.autoLicense" />
							<span v-else>{{ row.autoLicense ||'-'}}</span>
						</template>
					</el-table-column>
					<el-table-column prop="cargoName" label="货物名称" width="140">
						<template #default="{row}">
							<el-input v-if="row.isEditing" v-model="row.cargoName" />
							<span v-else>{{ row.cargoName ||'-'}}</span>
						</template>
					</el-table-column>
					<el-table-column prop="shippingCompany" label="发货厂家" width="140">
						<template #default="{row}">
							<!-- <el-input v-if="row.isEditing" v-model="row.shippingCompany" /> -->

							<el-select v-if="row.isEditing" v-model="row.shippingCompanyId" filterable
								:reserve-keyword="false" placeholder="请选择发货厂家" style="width: 120px" value-key="id"
								@change="handleCompanyChange(row, 'shipping')">
								<el-option v-for="item in caiOptions" :key="item.id" :label="item.companyName"
									:value="item.id">
									<span>{{ item.companyName }}</span>

								</el-option>
							</el-select>
							<span v-else>{{ row.shippingCompany ||'-'}}</span>
						</template>
					</el-table-column>
					<el-table-column prop="receivingCompany" label="收货厂家" width="140">
						<template #default="{row}">
							<!-- <el-input v-if="row.isEditing" v-model="row.receivingCompany" /> -->
							<el-select v-if="row.isEditing" v-model="row.receivingCompanyId" filterable
								:reserve-keyword="false" placeholder="请选择收货厂家" style="width: 120px" value-key="id"
								@change="handleCompanyChange(row, 'receiving')">
								<el-option v-for="item in xiaoOptions" :key="item.id" :label="item.companyName"
									:value="item.id">
									<span>{{ item.companyName }}</span>

								</el-option>
							</el-select>
							<span v-else>{{ row.receivingCompany ||'-'}}</span>
						</template>
					</el-table-column>

					<el-table-column prop="roughWeight" label="毛重" width="120">
						<template #default="{ row }">
							<el-tooltip class="box-item" effect="dark" content="输入完成回车重新计算" placement="top-start"
								v-if="row.isEditing">
								<el-input type="text" v-model="row.roughWeight" placeholder="请输入毛重（如20.05）" @input="(val) => {
			        
			          const validVal = val.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace(/^\./, '');
			          const decimalIndex = validVal.indexOf('.');
			          const filteredVal = decimalIndex !== -1 ? validVal.slice(0, decimalIndex + 3) : validVal;
			          row.roughWeight = filteredVal; 
			        }" @blur="() => {
			          const numVal = row.roughWeight === '' ? 0 : Number(row.roughWeight);
			          row.roughWeight = Number(numVal.toFixed(2)); 
			          calculateSuttle(row); 
			        }" @keyup.enter="() => {
			        
			          const numVal = row.roughWeight === '' ? 0 : Number(row.roughWeight);
			          row.roughWeight = Number(numVal.toFixed(2));
			          calculateSuttle(row);
			        }" />
							</el-tooltip>
							<span v-else>{{ row.roughWeight !== undefined ? row.roughWeight : '-' }}</span>
						</template>
					</el-table-column>
					<el-table-column prop="tare" label="皮重" width="120">
						<template #default="{ row }">
							<el-tooltip class="box-item" effect="dark" content="输入完成回车重新计算" placement="top-start"
								v-if="row.isEditing">
								<el-input type="text" v-model="row.tare" placeholder="请输入皮重（如31.04）" @input="(val) => {
				         
				          const validVal = val.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace(/^\./, '');
				          const decimalIndex = validVal.indexOf('.');
				          const filteredVal = decimalIndex !== -1 ? validVal.slice(0, decimalIndex + 3) : validVal;
				          row.tare = filteredVal; 
				        }" @blur="() => {
				          const numVal = row.tare === '' ? 0 : Number(row.tare);
				          row.tare = Number(numVal.toFixed(2));
				          calculateSuttle(row);
				        }" @keyup.enter="() => {
				        
				          const numVal = row.tare === '' ? 0 : Number(row.tare);
				          row.tare = Number(numVal.toFixed(2));
				          calculateSuttle(row);
				        }" />
							</el-tooltip>
							<span v-else>{{ row.tare !== undefined ? row.tare : '-' }}</span>
						</template>
					</el-table-column>
					<el-table-column prop="suttle" label="净重" width="120">
						<template #default="{row}">
							<el-input v-if="row.isEditing" v-model="row.suttle" disabled />
							<span v-else>{{ row.suttle ||'-'}}</span>
						</template>
					</el-table-column>
					<el-table-column prop="settlementSuttle" label="结算净重" width="120">
						<template #default="{row}">
							<el-input v-if="row.isEditing" v-model="row.settlementSuttle" disabled />
							<span v-else>{{ row.settlementSuttle ||'-'}}</span>
						</template>
					</el-table-column>
					<el-table-column prop="specifications" label="规格" width="100">
						<template #default="{row}">
							<el-input v-if="row.isEditing" v-model="row.specifications" />
							<span v-else>{{ row.specifications ||'-'}}</span>
						</template>
					</el-table-column>
					<el-table-column prop="driverName" label="司机姓名" width="90">
						<template #default="{row}">
							<el-input v-if="row.isEditing" v-model="row.driverName" />
							<span v-else>{{ row.driverName ||'-'}}</span>
						</template>
					</el-table-column>
					<el-table-column prop="weigher" label="司磅员" width="90">
						<template #default="{row}">
							<el-input v-if="row.isEditing" v-model="row.weigher" />
							<span v-else>{{ row.weigher ||'-'}}</span>
						</template>
					</el-table-column>
					<el-table-column prop="weighingType" label="过磅类型" width="90">
						<template #default="{row}">
							<span>{{ row.weighingType === 1 ? '采购' : '销售' }}</span>
						</template>
					</el-table-column>
					<el-table-column prop="weightStatus" label="状态" width="160">
						<template #default="{row}">
							<span>{{ getStatusText(row.weightStatus)  ||'-'}}</span>
						</template>
					</el-table-column>

					<el-table-column label="操作" width="290" fixed="right">
						<template #default="{row}">
							<el-button v-if="row.isEditing" type="success" size="small" @click="handleSave(row)">
								保存
							</el-button>
							<el-button v-if="row.isEditing" type="info" size="small" @click="handleCancelEdit(row)">
								取消
							</el-button>
							<el-button v-if="!row.isEditing && row.weightStatus===2" type="primary" size="small"
								@click="handleEdit(row)">
								编辑
							</el-button>
							<el-button v-if="row.weightStatus != 0 && !row.isEditing" type="success" size="small"
								@click="handleRollback(row)">
								回退
							</el-button>
							<el-button v-if="!row.isEditing && role==='3' " type="info" size="small"
								@click="handleView(row)">
								查看
							</el-button>
							<el-button v-if="!row.isEditing && row.weightStatus===2" type="info" size="small"
								@click="handlePrint(row)">
								打印
							</el-button>
						</template>
					</el-table-column>
				</el-table>
				<div style="margin-top: 5px; display: flex;flex-direction:row-reverse;">
					<el-pagination v-if="hstotal>0" v-model:current-page="hslistQuery.current"
						v-model:page-size="hslistQuery.size" :page-sizes="[5, 8, 10]" :size="size" :background="false"
						layout="sizes, prev, pager, next" :total="hstotal" @size-change="handleSizeChange"
						@current-change="handleCurrentChange" />
				</div>
			</el-card>




		</div>




	</div>

	<el-dialog v-model="viewDialogVisible" title="详情查看" width="800px">
		<el-descriptions :column="2" border>
			<el-descriptions-item label="时间">{{ viewData?.secondAweighingTime || '-' }}</el-descriptions-item>
			<el-descriptions-item label="车牌号">{{ viewData?.autoLicense || '-' }}</el-descriptions-item>
			<el-descriptions-item label="货物名称">{{ viewData?.cargoName || '-' }}</el-descriptions-item>
			<el-descriptions-item label="过磅类型">
				{{ viewData?.weighingType === 1 ? '采购' : '销售' || '-' }}
			</el-descriptions-item>
			<el-descriptions-item label="原始皮重">{{ viewData?.relyTare || '-' }}</el-descriptions-item>
			<el-descriptions-item label="原始毛重">{{ viewData?.relyRoughWeight || '-' }}</el-descriptions-item>
			<el-descriptions-item label="原始净重">{{ viewData?.relySuttle || '-' }}</el-descriptions-item>
			<el-descriptions-item label="结算净重">{{ viewData?.settlementSuttle || '-' }}</el-descriptions-item>
			<el-descriptions-item label="规格">{{ viewData?.specifications || '-' }}</el-descriptions-item>
			<el-descriptions-item label="司机姓名">{{ viewData?.driverName || '-' }}</el-descriptions-item>
			<el-descriptions-item label="司磅员">{{ viewData?.weigher || '-' }}</el-descriptions-item>
			<el-descriptions-item label="状态">{{ getStatusText(viewData?.weightStatus) || '-' }}</el-descriptions-item>
		</el-descriptions>

		<template #footer>
			<div class="dialog-footer">
				<el-button @click="viewDialogVisible = false">关闭</el-button>
			</div>
		</template>
	</el-dialog>
	<!-- 称重计量单弹窗 -->
	<el-dialog v-model="dialogVisible" width="800px" class="print-dialog" :before-close="handleClose">
		<!-- 	<el-select v-model="poundTemplateType" placeholder="请选择磅单类型" style="margin-bottom: 20px;">
			<el-option label="盛虹入库" :value="1"></el-option>
			<el-option label="盛虹出库" :value="2"></el-option>
			<el-option label="天津大港入库" :value="3"></el-option>
			<el-option label="天津大港出库" :value="4"></el-option>
			<el-option label="默认磅单" :value="5"></el-option>
		</el-select> -->
		<div class="dybox">
			<!-- 磅单类型选择器 -->


			<!-- 盛虹入库模板 (1) -->
			<div v-if="poundTemplateType === 1" class="pound-template">
				<div class="header-info">
					<div style="text-align: center; font-weight: bold; font-size: 18px;">河北鸿科碳素有限公司</div>
					<div style="text-align: center; font-weight: bold; font-size: 14px;">过磅单</div>
				</div>
				<!-- 顶部信息 -->
				<div class="header-info"
					style="font-family: SimSun, serif; margin-bottom: 10px; display: flex; justify-content: space-between;">
					<div>打印时间：{{ editableData.nowTime }}</div>
					<div>单位：吨</div>
					<div>No. {{ editableData.weightNumber }}</div>
				</div>

				<table class="print-table" border="1" cellspacing="0" cellpadding="3"
					style="width: 100%; border-collapse: collapse; font-family: SimSun; table-layout: fixed;">

					<tr>
						<td style="width: 20%;">单位名称</td>
						<td colspan="4" style="width: 80%;" data-field="shippingCompany">
							{{ editableData.shippingCompany }}
						</td>
					</tr>
					<tr>
						<td>车号</td>
						<td>货物名称</td>
						<td>毛重</td>
						<td>皮重</td>
						<td>净重</td>
					</tr>
					<tr>
						<td data-field="autoLicense">{{ editableData.autoLicense }}</td>
						<td data-field="cargoName">{{ editableData.cargoName }}</td>
						<td data-field="roughWeight">{{ editableData.roughWeight }}</td>
						<td data-field="tare">{{ editableData.tare }}</td>
						<td data-field="suttle">{{ editableData.suttle }}</td>
					</tr>
					<tr>
						<td colspan="1">备注</td>
						<td colspan="2"></td>
						<td>司磅</td>
						<td data-field="weigher">{{ editableData.weigher }}</td>
					</tr>

				</table>
			</div>

			<!-- 盛虹出库模板 (2) -->
			<div v-if="poundTemplateType === 2" class="pound-template">
				<div class="header-info">

					<div style="text-align: center; font-weight: bold; font-size: 14px;">过磅单</div>
				</div>
				<!-- 顶部信息 -->
				<div class="header-info"
					style="font-family: SimSun, serif; margin-bottom: 10px; display: flex; justify-content: space-between;">
					<div>打印时间：{{ editableData.nowTime }}</div>
					<div>单位：吨</div>
					<div>No. {{ editableData.weightNumber }}</div>
				</div>
				<table class="print-table" border="1" cellspacing="0" cellpadding="3"
					style="width: 100%; border-collapse: collapse; font-family: SimSun; table-layout: fixed;">

					<tr>
						<td style="width: 20%;">单位名称</td>
						<td colspan="4" style="width: 80%;" data-field="shippingCompany">
							{{ editableData.shippingCompany }}
						</td>
					</tr>
					<tr>
						<td>车号</td>
						<td>货物名称</td>
						<td>毛重</td>
						<td>皮重</td>
						<td>净重</td>
					</tr>
					<tr>
						<td data-field="autoLicense">{{ editableData.autoLicense }}</td>
						<td data-field="cargoName">{{ editableData.cargoName }}</td>
						<td data-field="roughWeight">{{ editableData.roughWeight }}</td>
						<td data-field="tare">{{ editableData.tare }}</td>
						<td data-field="suttle">{{ editableData.suttle }}</td>
					</tr>
					<tr>
						<td colspan="1">备注</td>
						<td colspan="2"></td>
						<td>司磅</td>
						<td data-field="weigher">{{ editableData.weigher }}</td>
					</tr>
				</table>
			</div>


			<!-- 天津大港入库模板 (3) -->
			<div v-if="poundTemplateType === 3" class="pound-template">
				<div class="header-info">
					<div style="text-align: center; font-weight: bold; font-size: 18px;">河北鸿科碳素有限公司</div>
					<div style="text-align: center; font-weight: bold; font-size: 14px;">入库单</div>
				</div>
				<!-- 顶部信息 -->
				<div class="header-info"
					style="font-family: SimSun, serif; margin-bottom: 10px; display: flex; justify-content: space-between;">
					<div>打印时间：{{ editableData.nowTime }}</div>
					<div>单位：吨</div>
					<div>No. {{ editableData.weightNumber }}</div>
				</div>
				<table class="print-table" border="1" cellspacing="0" cellpadding="3"
					style="width: 100%; border-collapse: collapse; font-family: SimSun; table-layout: fixed;">

					<tr>
						<td style="width: 20%;">单位名称</td>
						<td colspan="4" style="width: 80%;" data-field="shippingCompany">
							{{ editableData.shippingCompany }}
						</td>
					</tr>
					<tr>
						<td>车号</td>
						<td>货物名称</td>
						<td>毛重</td>
						<td>皮重</td>
						<td>净重</td>
					</tr>
					<tr>
						<td data-field="autoLicense">{{ editableData.autoLicense }}</td>
						<td data-field="cargoName">{{ editableData.cargoName }}</td>
						<td data-field="roughWeight">{{ editableData.roughWeight }}</td>
						<td data-field="tare">{{ editableData.tare }}</td>
						<td data-field="suttle">{{ editableData.suttle }}</td>
					</tr>
					<tr>
						<td colspan="1">备注</td>
						<td colspan="2"></td>
						<td>司磅</td>
						<td data-field="weigher">{{ editableData.weigher }}</td>
					</tr>
				</table>
			</div>

			<!-- 天津大港出库模板 (4) -->
			<div v-if="poundTemplateType === 4" class="pound-template">
				<div class="header-info">
					<div style="text-align: center; font-weight: bold; font-size: 18px;">河北鸿科碳素有限公司</div>
					<div style="text-align: center; font-weight: bold; font-size: 14px;">过磅单</div>
				</div>
				<!-- 顶部信息 -->
				<div class="header-info"
					style="font-family: SimSun, serif; margin-bottom: 10px; display: flex; justify-content: space-between;">
					<div>打印时间：{{ editableData.nowTime }}</div>
					<div>单位：吨</div>
					<div>No. {{ editableData.weightNumber }}</div>
				</div>
				<table class="print-table" border="1" cellspacing="0" cellpadding="3"
					style="width: 100%; border-collapse: collapse; font-family: SimSun; table-layout: fixed;">

					<tr>
						<td style="width: 16%;">单位名称</td>
						<td colspan="5" style="width: 84%;" data-field="shippingCompany">
							{{ editableData.shippingCompany }}
						</td>
					</tr>
					<tr>
						<td>车号</td>
						<td>货物名称</td>
						<td>毛重</td>
						<td>皮重</td>
						<td>净重</td>
						<td>结算量</td>
					</tr>
					<tr>
						<td data-field="autoLicense">{{ editableData.autoLicense }}</td>
						<td data-field="cargoName">{{ editableData.cargoName }}</td>
						<td data-field="roughWeight">{{ editableData.roughWeight }}</td>
						<td data-field="tare">{{ editableData.tare }}</td>
						<td data-field="suttle">{{ editableData.suttle }}</td>
						<td>{{ editableData.settlementSuttle }}</td>
					</tr>
					<tr>
						<td colspan="1">备注</td>
						<td colspan="2"></td>
						<td>司磅</td>
						<td colspan="2" data-field="weigher">{{ editableData.weigher }}</td>
					</tr>
				</table>
			</div>

			<!-- 默认模板 (5) -->
			<div v-if="poundTemplateType === 5" class="default-template">
				<div class="header-info">
					<div style="text-align: center; font-weight: bold; font-size: 18px;">河北鸿科碳素有限公司</div>
					<div style="text-align: center; font-weight: bold; font-size: 14px;">称重计量单</div>
				</div>
				<!-- 顶部信息 -->
				<div class="header-info"
					style="font-family: SimSun, serif; margin-bottom: 10px; display: flex; justify-content: space-between;">
					<div>打印时间：{{ editableData.nowTime }}</div>
					<div>No. {{ editableData.weightNumber }}</div>
				</div>
				<!-- 核心表格 -->
				<table class="print-table" border="1" cellspacing="0" cellpadding="3"
					style="width: 100%; border-collapse: collapse; font-family: SimSun; table-layout: fixed;">
					<tr>
						<td style="width: 12%;">车号：</td>
						<td style="width: 13%;" data-field="autoLicense">{{ editableData.autoLicense }}</td>
						<td style="width: 12%;">发货单位：</td>
						<td colspan="5" style="width: 63%;" data-field="shippingCompany">
							{{ editableData.shippingCompany }}
						</td>
					</tr>
					<tr>
						<td style="width: 12%;">货名：</td>
						<td style="width: 13%;" data-field="cargoName">{{ editableData.cargoName }}</td>
						<td style="width: 12%;">收货单位：</td>
						<td colspan="5" style="width: 63%;" data-field="receivingCompany">
							{{ editableData.receivingCompany }}
						</td>
					</tr>
					<tr>
						<td style="width: 12%;">毛重：</td>
						<td style="width: 13%;" data-field="roughWeight">{{ editableData.roughWeight }}</td>
						<td style="width: 12%;">皮重：</td>
						<td style="width: 13%;" data-field="tare">{{ editableData.tare }}</td>
						<td style="width: 12%;">净重：</td>
						<td style="width: 13%;" data-field="suttle">{{ editableData.suttle }}</td>
						<td style="width: 12%;">结算净重：</td>
						<td style="width: 13%;" data-field="settlementWeight">{{ editableData.settlementSuttle }}</td>
					</tr>
					<tr>
						<td style="width: 12%;">毛重时间：</td>
						<td colspan="3" style="width: 38%;"
							:data-field="editableData.weighingType===1?editableData.aweighingNameTime:editableData.secondAweighingTime">
							{{editableData.weighingType===1?editableData.aweighingNameTime:editableData.secondAweighingTime }}
						</td>
						<td style="width: 12%;">皮重时间：</td>
						<td colspan="3" style="width: 38%;"
							:data-field="editableData.weighingType===2?editableData.aweighingNameTime:editableData.secondAweighingTime">
							{{editableData.weighingType===2?editableData.aweighingNameTime:editableData.secondAweighingTime}}
						</td>
					</tr>
					<tr>
						<td style="width: 12%;">司机：</td>
						<td style="width: 13%;" data-field="driverName">{{ editableData.driverName }}</td>
						<td style="width: 12%;">规格：</td>
						<td style="width: 13%;" data-field="specifications">{{ editableData.specifications }}</td>
						<td style="width: 12%;">司磅员：</td>
						<td colspan="3" style="width: 38%;" data-field="weigher">{{ editableData.weigher }}</td>
					</tr>
				</table>
			</div>
			<div v-if="poundTemplateType === 6" class="pound-template">
				<div class="header-info">

					<div style="text-align: center; font-weight: bold; font-size: 14px;">过磅单</div>
				</div>
				<!-- 顶部信息 -->
				<div class="header-info"
					style="font-family: SimSun, serif; margin-bottom: 10px; display: flex; justify-content: space-between;">
					<div>打印时间：{{ editableData.nowTime }}</div>
					<div>单位：吨</div>
					<!-- <div>No. {{ editableData.weightNumber }}</div> -->
				</div>
				<table class="print-table" border="1" cellspacing="0" cellpadding="3"
					style="width: 100%; border-collapse: collapse; font-family: SimSun; table-layout: fixed;">

					<tr>
						<td style="width: 20%;">单位名称</td>
						<td colspan="4" style="width: 80%;" data-field="shippingCompany">
							<!-- 	中石油燃料油有限责任公司华北销售分公司 -->
							{{ editableData.shippingCompany }}
						</td>
					</tr>
					<tr>
						<td>车号</td>
						<td>货物名称</td>
						<td>毛重</td>
						<td>皮重</td>
						<td>净重</td>
					</tr>
					<tr>
						<td data-field="autoLicense">{{ editableData.autoLicense }}</td>
						<td data-field="cargoName">{{ editableData.cargoName }}</td>
						<td data-field="roughWeight">{{ editableData.roughWeight }}</td>
						<td data-field="tare">{{ editableData.tare }}</td>
						<td data-field="suttle">{{ editableData.suttle }}</td>
					</tr>
					<tr>
						<td colspan="1">备注</td>
						<td colspan="2"></td>
						<td>司磅</td>
						<td data-field="weigher">{{ editableData.weigher }}</td>
					</tr>
				</table>
			</div>
		</div>

		<!-- 操作按钮 -->
		<template #footer>
			<div class="dialog-footer" style="text-align: right; margin-top: 10px;">
				<el-button type="success" @click="handleDPrint">打印</el-button>
				<el-button @click="dialogVisible = false">取消</el-button>
			</div>
		</template>
	</el-dialog>

</template>

<script setup lang="ts">
	import {
		ref,
		reactive,
		onMounted,
		nextTick,
		onBeforeUnmount,
		getCurrentInstance,
		computed
	} from 'vue';
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus'
	import type { ComponentSize } from 'element-plus'
	import { ArrowLeft } from '@element-plus/icons-vue'
	const size = ref<ComponentSize>('default')
	import cloneDeep from 'lodash/cloneDeep';
	import { useRouter } from 'vue-router'
	const router = useRouter()
	const {
		proxy
	} = getCurrentInstance()
	interface TableItem {
		updateTime : string
		autoLicense : string
		cargoName : string
		tare : number
		roughWeight : number
		suttle : number
		isEditing ?: boolean
		driverName : string
		specifications : string
		receivingCompany : string
		shippingCompany : string
		receivingCompanyId : string
		shippingCompanyId : string
		weigher : string
		weighingType : number
		originalData ?: Partial<TableItem>
	}
	interface CompanyOption {
		companyName : string
		id : string
	}
	const caiOptions = ref<CompanyOption[]>([

	])
	const xiaoOptions = ref<CompanyOption[]>([

	])
	const options = [
		{
			value: 0,
			label: '未过磅',
		},
		{
			value: 1,
			label: '一次过磅完成',
		},
		{
			value: 2,
			label: '二次过磅完成',
		},

	]
	const viewDialogVisible = ref(false);
	const viewData = ref<TableItem | null>(null);
	// 弹窗状态
	const dialogVisible = ref(false)
	const poundTemplateType = ref(5);
	// 编辑状态
	const isEditing = ref(false)
	const tableData = ref<TableItem[]>([


	])
	const role = localStorage.getItem('role');
	const editableFields = ['grossWeight', 'tareWeight', 'netWeight', 'driver', 'spec', 'weigher', 'carNo', 'goodsName', 'sender', 'receiver']
	// 原始数据
	let initialData = reactive({})
	let editableData = reactive({ ...initialData })

	const formInline = reactive({
		weighingDate: '',
		autoLicense: '',
		weightStatus: null,
		// 新增：货物名称（输入框绑定）
		cargoName: '',
		// 新增：发货单位ID（下拉选择绑定，与后台接口参数对齐）
		shippingCompanyId: '',
		// 新增：收货单位ID（下拉选择绑定，与后台接口参数对齐）
		receivingCompanyId: ''

	})

	const hslistQuery = reactive({
		current: 1,
		size: 5,

	})
	const handleBack = () => {
		router.go(-1)
	}
	const getStatusText = (status) => {
		const map = {
			0: '未过磅',
			1: '一次过磅完成',
			2: '二次过磅完成'
		}
		return map[status] || '未知'
	}
	const calculateSuttle = (row) => {
		// 强制转为数字（避免字符串计算）
		const formattedRoughWeight = row.roughWeight ? Number(row.roughWeight) : 0;
		const formattedTare = row.tare ? Number(row.tare) : 0;

		// 保留2位小数（最终计算结果格式化）
		row.roughWeight = Number(formattedRoughWeight.toFixed(2));
		row.tare = Number(formattedTare.toFixed(2));

		// 计算净重和结算净重
		if (formattedRoughWeight >= 0 && formattedTare >= 0) {
			const suttle = Number((formattedRoughWeight - formattedTare).toFixed(2));
			row.suttle = suttle;
			row.settlementSuttle = Number((suttle * (row.countSuttle || 1)).toFixed(2));
		} else {
			row.suttle = 0;
			row.settlementSuttle = 0;
		}
	};
	// const calculateSuttle = (row) => {
	// 	// 1. 先格式化毛重、皮重（确保两位小数，避免非数字值）
	// 	const formattedRoughWeight = row.roughWeight ? Number(Number(row.roughWeight).toFixed(2)) : 0;
	// 	const formattedTare = row.tare ? Number(Number(row.tare).toFixed(2)) : 0;

	// 	// 2. 更新行数据中的毛重、皮重（确保显示格式化后的值）
	// 	row.roughWeight = formattedRoughWeight;
	// 	row.tare = formattedTare;

	// 	// 3. 计算净重（毛重 - 皮重）并格式化
	// 	if (formattedRoughWeight && formattedTare) {
	// 		const suttle = Number((formattedRoughWeight - formattedTare).toFixed(2));
	// 		row.suttle = suttle;

	// 		// 4. 计算结算净重（净重 * countSuttle）并格式化
	// 		const settlementSuttle = Number((suttle * (row.countSuttle || 1)).toFixed(2));
	// 		row.settlementSuttle = settlementSuttle;
	// 	} else {
	// 		row.suttle = 0; // 无数据时默认0（避免显示null/undefined）
	// 		row.settlementSuttle = 0;
	// 	}
	// };
	const handleCancelEdit = (row : TableItem) => {
		// 1. 恢复编辑前的原始数据（编辑时已保存到originalData）
		if (row.originalData) {
			Object.assign(row, row.originalData);
			// 清除原始数据缓存，避免下次编辑干扰
			delete row.originalData;
		}
		// 2. 退出编辑状态
		row.isEditing = false;
	};
	const handleRollback = async (row : TableItem) => {
		// 定义回退确认文案（根据当前状态动态生成）
		const confirmText = row.weightStatus === 1
			? "是否确认回退至【未过磅】状态？"
			: "是否确认回退至【一次过磅】状态？";

		try {
			// 1. 弹出确认弹窗
			await ElMessageBox.confirm(
				confirmText,
				"回退确认",
				{
					confirmButtonText: "确认回退",
					cancelButtonText: "取消",
					type: "warning" // 警告类型弹窗，增强视觉提示
				}
			);

			// 2. 确认后调用回退接口（rollbackWeighing）
			const res = await proxy.$request.rollbackWeighing({
				id: row.id // 接口参数：仅需行ID
			});

			// 3. 接口成功处理
			if (res?.data?.code === 200) {
				ElMessage.success("回退成功！");
				// 4. 重新拉取列表，刷新数据状态
				const params = Object.assign({}, formInline, hslistQuery);
				fetchData(params);
			} else {
				// 接口返回非成功状态（如业务异常）
				ElMessage.error(res?.data?.message || "回退失败，请重试");
			}
		} catch (error : any) {
			// 5. 异常处理（包括用户取消弹窗、网络错误等）
			if (error.name === "MessageBoxCancel") {
				// 用户点击取消按钮，不提示
				return;
			}
			// 其他错误（网络异常、接口报错）
			console.error("回退接口调用失败：", error);
			ElMessage.error(error.data?.message || "网络异常，回退操作失败");
		}
	};
	const fetchData = async (params) => {
		try {


			const res = await proxy.$request.getHisList(params)

			if (res?.data?.code === 200) {
				tableData.value = res.data.result?.resultData || []
				hstotal.value = res.data.result?.totalRows || 0
			} else {
				ElMessage.error(res?.data?.message || '请求失败')
			}
		} catch (error : any) {
			console.error('API请求错误:', error)
			ElMessage.error(error.data.message || '网络请求异常')
		}
	}
	const handleCompanyChange = async (row : TableItem, type : 'shipping' | 'receiving') => {
		// 1. 获取当前选择的厂家ID（发货取shippingCompanyId，收货取receivingCompanyId）
		const companyId = type === 'shipping' ? row.shippingCompanyId : row.receivingCompanyId;
		if (!companyId) return; // 若未选择厂家，不执行后续逻辑

		try {
			// 2. 调用接口获取最新的countSuttle（与handleEdit逻辑一致，复用接口）
			const res = await proxy.$request.getCompanySelect({ id: companyId });
			if (res.data.code === 200) {
				// 3. 更新当前行的countSuttle（默认1 if 接口无返回）
				row.countSuttle = res.data.result?.[0]?.suttle || 1;
				// 4. 重新计算净重和结算净重（并自动格式化两位小数）
				calculateSuttle(row);
			} else {
				row.countSuttle = 1; // 接口失败时默认countSuttle为1
				ElMessage.error(res.data.message || '获取厂家结算系数失败');
			}
		} catch (error : any) {
			row.countSuttle = 1;
			console.error('获取厂家结算系数异常:', error);
			ElMessage.error(error.data?.message || '网络请求异常');
		}
	};

	const handleView = (row : TableItem) => {
		viewData.value = { ...row };
		viewDialogVisible.value = true;
	}
	const handleSizeChange = (val : number) => {
		hslistQuery.size = val;
		hslistQuery.current = 1;
		const params = Object.assign({}, formInline, hslistQuery);
		fetchData(params);
	}
	const handleCurrentChange = (val : number) => {
		hslistQuery.current = val;
		const params = Object.assign({}, formInline, hslistQuery)
		fetchData(params)
	}

	const onSubmit = () => {
		const params = Object.assign({}, formInline, hslistQuery)
		fetchData(params)
	}

	const handleInput = (e : Event) => {
		const cell = e.target as HTMLTableCellElement
		const field = cell.getAttribute('data-field')
		if (!field) return

		// 同步输入值到数据对象
		(editableData as any)[field] = cell.textContent?.trim() || ''

		// 根据字段触发对应的重量计算
		if (field === 'grossWeight') {
			calculateWeights('gross')
		} else if (field === 'tareWeight') {
			calculateWeights('tare')
		} else if (field === 'netWeight') {
			calculateWeights('net')
		}
	}
	const calculateWeights = (field : 'gross' | 'tare' | 'net') => {
		const gross = parseFloat(editableData.grossWeight) || 0
		const tare = parseFloat(editableData.tareWeight) || 0
		const net = parseFloat(editableData.netWeight) || 0

		// 根据修改的字段类型，计算其他两个字段
		if (field === 'gross') {
			// 修改了毛重，重新计算净重
			editableData.netWeight = (gross - tare).toString()
		} else if (field === 'tare') {
			// 修改了皮重，重新计算净重
			editableData.netWeight = (gross - tare).toString()
		} else if (field === 'net') {
			// 修改了净重，需要用户至少提供毛重或皮重中的一个
			if (gross > 0) {
				// 如果有毛重，计算皮重
				editableData.tareWeight = (gross - net).toString()
			} else if (tare > 0) {
				// 如果有皮重，计算毛重
				editableData.grossWeight = (net + tare).toString()
			}
		}
	}
	/**
	 * 进入编辑模式
	 */
	const handleDEdit = () => {
		isEditing.value = true
		nextTick(() => {
			const cells = document.querySelectorAll('.print-table td[data-field]') as NodeListOf<HTMLTableCellElement>
			cells.forEach(cell => {
				const field = cell.getAttribute('data-field') as string

				// 判断是否为可编辑字段
				if (editableFields.includes(field)) {
					cell.setAttribute('contenteditable', 'true')
					cell.style.backgroundColor = '#f5f7fa' // 可编辑字段背景色标识
					cell.addEventListener('input', handleInput) // 添加输入监听
				} else {
					cell.setAttribute('contenteditable', 'false')
					cell.style.backgroundColor = 'transparent' // 不可编辑字段无背景色
				}
			})
		})
	}

	/**
	 * 保存编辑
	 */
	const handleDSave = () => {
		// 1. 重量字段二次校验（确保数值有效性）
		const validateAndConvertWeight = (value : string) => {
			const num = parseFloat(value)
			return isNaN(num) ? '0' : num.toString()
		}

		// 对重量字段进行特殊处理
		editableData.grossWeight = validateAndConvertWeight(editableData.grossWeight)
		editableData.tareWeight = validateAndConvertWeight(editableData.tareWeight)
		editableData.netWeight = validateAndConvertWeight(editableData.netWeight)

		// 2. 自动重新计算净重（确保数据一致性）
		calculateWeights('gross') // 触发一次计算，确保净重正确

		// 3. 关闭编辑状态（无需操作DOM，依赖Vue响应式更新视图）
		isEditing.value = false

		// 4. 模拟保存到后端（实际项目中替换为API请求）
		console.log('保存成功，数据为：', { ...editableData })

		// 5. 提示用户保存结果
		ElMessage.success('数据保存成功')
	}
	const handleDPrint = () => {
		// 创建打印容器
		const printContainer = document.createElement('div')
		printContainer.innerHTML = document.querySelector('.dybox')!.outerHTML

		// 注入打印专用样式
		const style = document.createElement('style')
		style.innerHTML = `
		      /* 关键修改：彻底隐藏浏览器默认页眉 */
		      @page {
		        margin: 0; /* 清除默认页边距 */
		        size: auto; /* 使用自动尺寸 */
		      }
		      
		      /* 添加页面内容边距 */
		      body {
		        margin: 0.5cm; /* 减小内容边距 */
		        font-family: SimSun, serif;
		        font-size: 13px; /* 稍微减小字体大小 */
		        padding: 0;
		        line-height: 1.2; /* 减小行高 */
		      }
		
		      /* 隐藏浏览器默认页眉页脚 */
		      @media print {
		        @page {
		          margin: 0;
		        }
		        body {
		          margin: 0.5cm;
		          -webkit-print-color-adjust: exact;
		          print-color-adjust: exact;
		        }
		        
		        /* 针对不同浏览器的隐藏方案 */
		        @page :first {
		          margin-top: 0;
		        }
		        ::-webkit-scrollbar {
		          display: none;
		        }
		      }
		      
		      /* 表格样式调整 */
		      .pound-template, .default-template {
		        margin: 0;
		        padding: 0;
		      }
		      
		      .header-info {
		        margin-bottom: 5px; /* 减小标题间距 */
		      }
		      
		      .print-table {
		        width: 100%;
		        border-collapse: collapse;
		        border: 1px solid #000;
		        font-size: 13px; /* 表格字体大小 */
		        table-layout: fixed;
		      }
		      
		      .print-table td {
		        border: 1px solid #000;
		        padding: 3px 5px; /* 减小单元格内边距 */
		        height: 24px; /* 固定单元格高度 */
		        vertical-align: middle;
		        word-break: break-all; /* 允许长单词换行 */
		        overflow: hidden;
		      }
		      
		      /* 特定模板调整 */
		      .default-template .print-table td {
		        padding: 2px 4px; /* 默认模板更紧凑 */
		        height: 22px;
		      }
		      
		      .footer-sign {
		        margin-top: 15px;
		        display: flex;
		        justify-content: space-around;
		      }
		      .footer-sign div {
		        text-align: center;
		      }
		      .footer-sign div div {
		        border-top: 1px solid #000;
		        width: 100px; /* 调整签字栏宽度 */
		      }
		    `
		    printContainer.appendChild(style)

		// 打开新窗口打印
		const printWindow = window.open('', '_blank')
		if (printWindow) {
			// 使用空白标题避免"about:blank"
			printWindow.document.title = " ";

			printWindow.document.write(`
      <!DOCTYPE html>
      <html>
        <head>
          <title> </title>
          <style>
            /* 添加额外的打印样式保险 */
            @page { margin: 0; }
            body { margin: 1cm; }
          </style>
        </head>
        <body>
          ${printContainer.outerHTML}
        </body>
      </html>
    `);

			printWindow.document.close();

			// 添加延迟确保样式加载
			printWindow.onload = () => {
				printWindow.focus(); // 确保窗口获得焦点
				setTimeout(() => {
					printWindow.print();
					printWindow.close();
				}, 100);
			}
		}
	}
	const handleReset = () => {
		// 1. 清空formInline中的所有检索条件（恢复初始状态）
		formInline.weighingDate = '';       // 清空过磅时间
		formInline.autoLicense = '';        // 清空车牌号
		formInline.cargoName = '';          // 清空货物名称（新增条件）
		formInline.shippingCompanyId = '';  // 清空发货单位（新增条件）
		formInline.receivingCompanyId = ''; // 清空收货单位（新增条件）
		formInline.weightStatus = null;     // 清空过磅状态（注意：下拉框默认值为null，而非空字符串）

		// 2. 重置分页参数（回到第一页，保持原有页大小）
		hslistQuery.current = 1; // 页码重置为1
		// hslistQuery.size 保持不变（用户上次选择的页大小，无需重置）
		// 3. 携带清空后的参数，重新请求数据（展示默认列表）
		const params = Object.assign({}, formInline, hslistQuery);
		fetchData(params);
	};
	/**
	 * 打印功能（关键：严格还原打印样式）
	 */
	const getFormattedTime = () => {
		const now = new Date()
		const year = now.getFullYear()
		const month = String(now.getMonth() + 1).padStart(2, '0')
		const day = String(now.getDate()).padStart(2, '0')
		const hours = String(now.getHours()).padStart(2, '0')
		const minutes = String(now.getMinutes()).padStart(2, '0')
		const seconds = String(now.getSeconds()).padStart(2, '0')

		return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
	}
	const handlePrint = (row) => {


		proxy.$request.getPrintId({ deductingId: row.deductingId, weighingType: row.weighingType }).then((res => {

			if (res.data.code === 200) {

				if (res.data.result) {
					poundTemplateType.value = Number(res.data.result.modelKey)
					initialData = cloneDeep(row)

					initialData.nowTime = getFormattedTime()
					editableData = { ...initialData }
					dialogVisible.value = true
				} else {
					initialData = cloneDeep(row)

					initialData.nowTime = getFormattedTime()
					editableData = { ...initialData }
					dialogVisible.value = true
				}





			} else {

				ElMessage.error(res.data.message)
			}
		})).catch((err => {
			console.log('err', err)
			ElMessage.error(err.data.message);
		}))


		// console.log('a ', row)


	}

	/**
	 * 关闭弹窗
	 */
	const handleClose = () => {
		// 恢复原始数据
		Object.assign(editableData, initialData)

		isEditing.value = false
		dialogVisible.value = false
	}



	const hstotal = ref(5)


	const handleEdit = (row : TableItem) => {
		row.originalData = { ...row }; // 保存原始数据（用于取消编辑时恢复）
		row.isEditing = true;

		// 【新增】进入编辑时，先格式化现有重量字段（毛重、皮重、净重、结算净重）
		row.roughWeight = row.roughWeight ? Number(Number(row.roughWeight).toFixed(2)) : 0;
		row.tare = row.tare ? Number(Number(row.tare).toFixed(2)) : 0;
		row.suttle = row.suttle ? Number(Number(row.suttle).toFixed(2)) : 0;
		row.settlementSuttle = row.settlementSuttle ? Number(Number(row.settlementSuttle).toFixed(2)) : 0;

		// 原有接口请求逻辑（不变）
		proxy.$request.getCompanySelect({ id: row.weighingType === 1 ? row.shippingCompanyId : row.receivingCompanyId })
			.then((res) => {
				if (res.data.code === 200) {
					row.countSuttle = res.data.result?.[0]?.suttle || 1;
					calculateSuttle(row); // 重新计算（确保与countSuttle匹配）
				} else {
					row.countSuttle = 1;
					ElMessage.error(res.data.message);
				}
			})
			.catch((err) => {
				console.log('err', err);
				row.countSuttle = 1;
				ElMessage.error(err.data?.messgae || '获取厂家系数异常');
			});
	};

	const setHis = async (row) => {
		try {
			// 【新增】提交前格式化所有重量字段（最终校验）
			const formattedData = {
				autoLicense: row.autoLicense,
				cargoName: row.cargoName,
				shippingCompanyId: row.shippingCompanyId,
				id: row.id,
				weigher: row.weigher,
				roughWeight: Number(Number(row.roughWeight).toFixed(2)), // 毛重格式化
				tare: Number(Number(row.tare).toFixed(2)), // 皮重格式化
				suttle: Number(Number(row.suttle).toFixed(2)), // 净重格式化
				receivingCompanyId: row.receivingCompanyId,
				driverName: row.driverName,
				specifications: row.specifications,
				settlementSuttle: Number(Number(row.settlementSuttle).toFixed(2)) // 结算净重格式化
			};

			// 调用接口提交（使用格式化后的数据）
			const res = await proxy.$request.setHis(formattedData);
			if (res?.data?.code === 200) {
				row.isEditing = false;
				const params = Object.assign({}, formInline, hslistQuery);
				fetchData(params);
				ElMessage.success('修改成功');
			} else {
				ElMessage.error(res?.data?.message || '请求失败');
			}
		} catch (error : any) {
			console.error('API请求错误:', error);
			ElMessage.error(error.data?.message || '网络请求异常');
		}
	};


	const handleSave = (row : TableItem) => {

		setHis(row)



		// 这里可以添加保存到后端的逻辑

	}
	const getCompanyNameList = async (num) => {
		try {


			const res = await proxy.$request.getCompanySelect({ companyType: num })
			if (res?.data?.code === 200) {


				if (res.data.result) {
					if (num === 1) {
						caiOptions.value = []
						caiOptions.value = res.data.result
					}
					if (num === 2) {
						xiaoOptions.value = []
						xiaoOptions.value = res.data.result
					}
				}


			} else {
				ElMessage.error(res?.data?.message || '请求失败')
			}
		} catch (error : any) {
			console.error('API请求错误:', error)
			ElMessage.error(error.data.message || '网络请求异常')
		}
	}
	onMounted(async () => {
		const params = Object.assign({}, formInline, hslistQuery)
		fetchData(params)
		await Promise.all([
			getCompanyNameList(1),
			getCompanyNameList(2)
		])
	})


	onBeforeUnmount(() => {
		const cells = document.querySelectorAll('.print-table td[data-field]')
		cells.forEach(cell => cell.removeEventListener('input', handleInput))
	})
</script>

<style lang="scss" scoped>
	.pound-container {
		padding: 28px;

		box-sizing: border-box;
		position: relative;





		.pound-bottom {

			width: 100%;
			margin-top: 50px;

			max-height: 800px;
		}
	}
</style>